#include "network/ip_address.hpp"

#include <sstream>

#include <arpa/inet.h>

namespace ibox::network {

std::string IpAddress::FormatInvalid::Format(const std::string &str) {
    std::ostringstream oss;
    oss << "'" << str << "' is not IPv4 string";
    return oss.str();
}

std::string IpAddress::to_string() const {
    char ip_str_buff[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &m_ip, ip_str_buff, INET_ADDRSTRLEN);
    return ip_str_buff;
}

IpAddress IpAddress::from_string(const std::string &ip_str) {
    struct in_addr addr;
    auto ret = inet_aton(ip_str.c_str(), &addr);
    if (ret == 0) {
        throw FormatInvalid(ip_str);
    }
    return IpAddress(addr.s_addr);
}

IpAddress IpAddress::any() { return IpAddress(0); }

IpAddress IpAddress::loop() { return IpAddress(0x0100007F); }
} // namespace ibox::network
